﻿using _11._24._2014_AngularPractice.Data;
using _11._24._2014_AngularPractice.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace _11._24._2014_AngularPractice.Adapters.Data
{
    public class SearchDataAdapter : ISearchAdapter
    {
        public SearchViewModel Search(string searchText, int pageNum)
        {
            SearchViewModel model = new SearchViewModel();

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var q = db.Cars.AsQueryable();

                if (searchText != null)
                {
                    int year;

                    if (int.TryParse(searchText, out year))
                    {
                        q = q.Where(c => c.Make.Contains(searchText)
                        || c.Model.Contains(searchText)
                        || c.Year == year);
                    }
                    else
                    {
                        q = q.Where(c => c.Make.Contains(searchText)
                        || c.Model.Contains(searchText));
                    }
                }

                model.TotalCarCount = q.Count();
                model.CurrentCarList = q.Select(c => new CarViewModel
                {
                    Make = c.Make,
                    Model = c.Model,
                    Year = c.Year
                }).OrderBy(c => c.Make).Skip(3 * (pageNum - 1)).Take(3).ToList();
            }

            return model;
        }
    }
}